package com.rongshu.view.login.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.SpannableStringUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.login.contract.PasswordLoginView;
import com.rongshu.view.login.entity.PasswordLogin;
import com.rongshu.view.login.presenter.PasswordLoginPresenter;
import com.rongshu.view.web.LocalWebActivity;
import com.rongshu.widget.PhoneEditText;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.utils.SPUtils;
import com.utils.Utils;
import com.utils.constants.SPKey;
import com.utils.permissions.OnPermission;
import com.utils.permissions.XXPermissions;
import com.widget.titlebar.OnKeyboardListener;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

public class PasswordLoginActivity extends BaseActivity<PasswordLoginPresenter> implements PasswordLoginView {

    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.phone_ed)
    PhoneEditText phoneEd;
    @BindView(R.id.pwd_ed)
    EditText pwdEd;
    @BindView(R.id.show_pwd_switch)
    ImageView showPwdSwitch;
    @BindView(R.id.login_bt)
    TextView loginBt;
    @BindView(R.id.txt_hint_1)
    TextView txtHint1;
    @BindView(R.id.share_layout)
    LinearLayout shareLayout;
    @BindView(R.id.protocal_switch)
    CheckBox protocalSwitch;
    @BindView(R.id.protocol_tv)
    TextView protocolTv;
    @BindView(R.id.last_login_weixin)
    ImageView lastLoginWeixin;
    @BindView(R.id.last_login_qq)
    ImageView lastLoginQq;
    //request
    private final int REQUEST_CODE = 0x01;
    //是否显示密码
    private boolean isShowPwd = false;
    //type
    private int type = 0;
    //permission
    private String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        immersionBar.keyboardEnable(true, WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)  //软键盘自动弹出
                .setOnKeyboardListener(new OnKeyboardListener() {
                    @Override
                    public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
                        shareLayout.setVisibility(isPopup ? View.GONE : View.VISIBLE);
                    }
                });
        immersionBar.init();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_password_login;
    }

    @Override
    protected void initView() {
        ivClose.setVisibility(View.GONE);
        ivBack.setVisibility(View.VISIBLE);
        int preferences = SPUtils.getPreferences(Constant.LOGIN_WAY, 0);
        lastLoginWeixin.setVisibility(preferences == Constant.LOGIN_WAY_WECHAT ? View.VISIBLE : View.INVISIBLE);
        lastLoginQq.setVisibility(preferences == Constant.LOGIN_WAY_QQ ? View.VISIBLE : View.INVISIBLE);
        //富文本显示
        protocolTv.setText(SpannableStringUtils.addMoreForeColorSpan(protocolTv.getText().toString(),
                ContextCompat.getColor(this, R.color.color_4a4a4a_protocol), 7, 15, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //用户协议
                        Intent intent = new Intent(PasswordLoginActivity.this, LocalWebActivity.class);
                        intent.putExtra(Constant.INTENT_TITLE, "用户服务协议");
                        intent.putExtra(Constant.INTENT_H5, Common.USER_AGREEMETN);
                        startActivity(intent);
                    }
                }, 16, 22, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(PasswordLoginActivity.this, LocalWebActivity.class);
                        intent.putExtra(Constant.INTENT_TITLE, "隐私政策");
                        intent.putExtra(Constant.INTENT_H5, Common.PRIVACY_POLICY);
                        startActivity(intent);
                    }
                }));
        protocolTv.setMovementMethod(LinkMovementMethod.getInstance());
        protocolTv.setHighlightColor(getResources().getColor(android.R.color.transparent));
        setPresenter(new PasswordLoginPresenter(this), this);
        loginBt.setClickable(false);
        //默认选中协议
        protocalSwitch.setChecked(true);
        //默认显示上次登录的手机号码
        if (!TextUtils.isEmpty(SPUtils.getPreferences(SPKey.LAST_LOGIN_PHONE, ""))) {
            phoneEd.setText(SPUtils.getPreferences(SPKey.LAST_LOGIN_PHONE, ""));
            phoneEd.setSelection(phoneEd.getText().toString().length());
        }
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    public void getUserRegisterforMobilePwd(PasswordLogin passwordLogin) {
        if (passwordLogin.getErrCode() == 0) {
            //保存输入的手机号码
            SPUtils.putPreferences(SPKey.LAST_LOGIN_PHONE, phoneEd.getPhoneText());
            //保存userinfo
            PasswordLogin.ResponseBean responseBean = passwordLogin.getResponse();
            UserInfoUtils.saveUserInfo(passwordLogin);
            //是否需要修改昵称
            int diyici = responseBean.getDiyici();
            //笔名
            String biName = responseBean.getBi_name();
            if (diyici == 1) {
                SetPenNameActivity.toSetPenNameActivity(this, biName, responseBean.getAvatar());
            }
            //记录登录方式
            SPUtils.putPreferences(Constant.LOGIN_WAY, type == 0 ? Constant.LOGIN_WAY_PHONE : type);
            showKeyboard(false);
            setResult(RESULT_OK);
            finish();
        } else {
            toast(passwordLogin.getErrMsg());
        }
    }

    @OnTextChanged(value = R.id.phone_ed, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void phoneTextChanged(Editable editable) {
        loginBt.setBackgroundResource(getBtnState() ? R.drawable.shape_btn_3cc051 :
                R.drawable.shape_btn_8fe49d);
        loginBt.setClickable(getBtnState());
    }

    @OnTextChanged(value = R.id.pwd_ed, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void pwdTextChanged(Editable editable) {
        loginBt.setBackgroundResource(getBtnState() ? R.drawable.shape_btn_3cc051 :
                R.drawable.shape_btn_8fe49d);
        loginBt.setClickable(getBtnState());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                setResult(RESULT_OK);
                finish();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        shareLayout.setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.layout_close, R.id.txtLoginRequest, R.id.show_pwd_switch, R.id.login_bt,
            R.id.auth_code_login, R.id.forget_pwd, R.id.iv_weixin, R.id.iv_xinlang, R.id.iv_qq})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_close:
                showKeyboard(false);
                finish();
                break;
            case R.id.txtLoginRequest:
                startActivity(new Intent(this, LoginQuestionActivity.class));
                break;
            case R.id.show_pwd_switch:
                if (isShowPwd) {
                    //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                    //mEtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    isShowPwd = false;
                    showPwdSwitch.setImageResource(R.drawable.eye_close_icon);
                    pwdEd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                    //选择状态 显示明文--设置为可见的密码
                    //mEtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    isShowPwd = true;
                    showPwdSwitch.setImageResource(R.drawable.eye_open_icon);
                    //此时隐藏，进行显示
                    pwdEd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                pwdEd.setSelection(pwdEd.getText().toString().length());
                break;
            case R.id.login_bt:
                if (!protocalSwitch.isChecked()) {
                    toast("请同意用户协议和隐私政策");
                    return;
                }
                presenter.getUserRegisterforMobilePwd(phoneEd.getPhoneText(),
                        pwdEd.getText().toString());
                break;
            case R.id.auth_code_login:
                showKeyboard(false);
                finish();
                break;
            case R.id.forget_pwd:
                startActivityForResult(new Intent(PasswordLoginActivity.this, ForgetPasswordActivity.class), REQUEST_CODE);
                break;
            case R.id.iv_weixin:
                bindThirdAccount(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.iv_xinlang:
                bindThirdAccount(SHARE_MEDIA.SINA);
                break;
            case R.id.iv_qq:
                bindThirdAccount(SHARE_MEDIA.QQ);
                break;
        }
    }

    private boolean getBtnState() {
        return phoneEd.getText().toString().length() == 13 && !TextUtils.isEmpty(pwdEd.getText().toString());
    }

    /**
     * 第三方账号登录绑定
     */
    private void bindThirdAccount(SHARE_MEDIA shareMedia) {
        if (shareMedia == SHARE_MEDIA.SINA) {
            if (!Utils.isWBInstall(this)) {
                toast("\"新浪微博\"不可用\n请检查手机是否安装\"新浪微博\"");
                return;
            }
        }
        if (!XXPermissions.isHasPermission(this, mPermissionList)) {
            XXPermissions.with(this).permission(mPermissionList).request(new OnPermission() {
                @Override
                public void hasPermission(List<String> granted, boolean isAll) {
                    UMShareAPI.get(PasswordLoginActivity.this)
                            .deleteOauth(PasswordLoginActivity.this, shareMedia, authListener);
                }

                @Override
                public void noPermission(List<String> denied, boolean quick) {
                }
            });
        } else {
            UMShareAPI.get(this).deleteOauth(this, shareMedia, authListener);
        }
    }

    UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            if (map != null) {
                String open_id = "";
                //类别(1QQ 2微信 3微博)
                switch (share_media) {
                    case QQ:
                        type = 1;
                        open_id = map.get("openid");
                        break;
                    case WEIXIN:
                        type = 2;
                        open_id = map.get("openid");
                        break;
                    case SINA:
                        type = 3;
                        open_id = map.get("uid");
                        break;
                }
                //昵称
                String nickname = map.get("name");
                //头像
                //第三方授权返回的用户头像
                String headPortraits = map.get("iconurl");
                //手机号
                String mobile = null;
                //registrationid
                String registrationid = UserInfoUtils.getRegistrationId();
                //登录
                presenter.thirdPartyLogin(type, registrationid, open_id, nickname, headPortraits, mobile);
            } else {
                UMShareAPI.get(PasswordLoginActivity.this).getPlatformInfo(PasswordLoginActivity.this, share_media, authListener);
            }
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            toast(throwable.getMessage());
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {

        }
    };
}
